package com.bgys.common.utils;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil {
    public static String toJson(Object obj) {
        return JSON.toJSONString(obj);
    }

    public static void print(Object obj) {
        System.out.println(toJson(obj));
    }

    /**
     * list转成json
     * @param list
     * @return
     */
    public static <T> String listToJson(List<T> list) {
        StringBuffer sb = new StringBuffer();

        list.forEach(d -> {
            sb.append(toJson(d));
            sb.append("\n");
        });

        return sb.toString();
    }

    public static <T> List formatList(List<String> list, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        list.forEach(d -> {
            result.add(fromJson(d, clazz));
        });
        return result;
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        return JSON.parseObject(json, clazz);
    }
}
